﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Net.NetworkInformation;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Coding4Fun.Phone.Controls;

namespace RadarGlobal.UIView
{
    public partial class GroupDlg : PhoneApplicationPage
    {
        ApplicationBarController barControl;

        Status myStatus = new Status();

        public GroupDlg()
        {
            InitializeComponent();

            InitializeControl();

            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Please check data connect wifi/cellular...");

                return;
            }
            pivotMe.Header = "My Group";
            pivotAll.Header="All";
        }

        private void InitializeControl()
        {
            barControl = new ApplicationBarController(this.ApplicationBar);

            barControl.AddNewButton("Join", "/icons/appbar.join.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("Delete", "/icons/appbar.delete.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("Create", "/icons/appbar.add.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("Find", "/icons/appbar.feature.search.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("Refresh", "/icons/appbar.refresh.rest.png", true, ApplicationBarButton_Click);

            LoadListGroup();

            LoadAllGroup();

            LoadInvateGroup();
        }
        private async void LoadInvateGroup()
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                return;
            }

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.GetListGroupInvateAsync(Global.UserInfo.UserID);

            client.GetListGroupInvateCompleted += (s, args) =>
            {
                if (args.Result == null) return;

                List<List<string>> listdata = JsonConvert.DeserializeObject<List<List<string>>>(args.Result);

                invateGroup.Items.Clear();

                var data = Group.DeserializeObject(listdata);

                foreach (Group item in data)

                    if (item.Status == 1)

                        invateGroup.Items.Add(item);
            };
        }

        private void LoadListGroup()
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                return;
            }

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.GetListGroupAsync(Global.UserInfo.Username);

            client.GetListGroupCompleted += (s, args) =>
            {
                if (args.Result == null) return;

                List<List<string>> listdata = JsonConvert.DeserializeObject<List<List<string>>>(args.Result);

                myGroup.Items.Clear();

                var data=Group.DeserializeObject(listdata);

                foreach (Group item in data)

                    if (item.Status == 1)

                        myGroup.Items.Add(item);
            };
        }

        private void LoadAllGroup()
        {
            myStatus.ShowPopup("waitting loading group data in server ...!");

            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                return;
            }

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.GetAllGroupAsync(0,30);

            client.GetAllGroupCompleted += (s, args) =>
            {
                allGroup.Items.Clear();

                List<List<string>> listdata = JsonConvert.DeserializeObject<List<List<string>>>(args.Result);

                var data = Group.DeserializeObject(listdata);

                foreach (Group item in data)

                    allGroup.Items.Add(item);

                myStatus.Abort();    
            };
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int i = MainPriviot.SelectedIndex;
            switch (i)
            {
                case 0:
                    barControl.ShowButtons("Create","Refresh");
                    break;
                case 1:
                    barControl.ShowButtons("Create", "Find","Refresh");
                    break;
                case 2:
                    barControl.ShowButtons("Refresh");
                    break;
            }
        }

        private void JoinGroup_Click(object sender, RoutedEventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Please check data connect wifi/cellular...");

                return;
            }

            string header = (sender as MenuItem).Header.ToString();

            ListBoxItem listItem = this.allGroup.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

            if (listItem != null)
            {
                mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

                Group item = listItem.Content as Group;

                client.CreateLinkerAsync(item.Id, Global.UserInfo.UserID, 0, 2);

                client.CreateLinkerCompleted += (s, args) =>
                {
                    MessageBox.Show("Your request has been sent successfully! Please wait for confirmation.");

                    LoadListGroup();
                };
            }
        }

        private void allGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(allGroup.SelectedItem!=null)
            {
                barControl.ShowButtons("Create", "Find", "Refresh");

                //barControl.ShowButtons("Xin vào", "Tạo nhóm", "Tìm kiếm","làm tươi");
            }
            else
                barControl.ShowButtons("Create","Find");
        }

        private void ExitGroup_Click(object sender, RoutedEventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Please check data connect wifi/cellular...");

                return;
            }
            string header = (sender as MenuItem).Header.ToString();

            ListBoxItem listItem = this.myGroup.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

            if (listItem != null)
            {
                mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

                Group item = listItem.Content as Group;

                if (item.MyOwner == 1)
                {
                    MessageBoxResult result = MessageBox.Show("You are the leader, if you leave the group, the group will be disbanded", "Are you want leave group?", MessageBoxButton.OKCancel);

                    if (result == MessageBoxResult.OK)
                    {
                        client.RemoveGroupAsync(item.Id);

                        client.RemoveGroupCompleted += (s, args) =>
                        {
                            if (args.Result == true)
                            {
                                MessageBox.Show("Group:" + item.Title + " is disbanded");

                                LoadListGroup();

                                LoadAllGroup();
                            }
                        };
                    }
                }
                else
                {
                    MessageBoxResult result = MessageBox.Show("Are you sure you want to leave the group.", "Are you want leave group?", MessageBoxButton.OKCancel);

                    if (result == MessageBoxResult.OK)
                    {
                        client.RemoveLinkerAsync(item.Id, Global.UserInfo.UserID);

                        client.RemoveLinkerCompleted += (s, args) =>
                        {
                            if (args.Result == true)
                            {
                                MessageBox.Show("You have left successful groups:" + item.Title);

                                LoadListGroup();
                            }
                        };
                    }
                }
            }
        }

        private void ApplicationBarButton_Click(object sender, EventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Please check data connect wifi/cellular...");

                return;
            }

            ApplicationBarIconButton btn = (ApplicationBarIconButton)sender;

            string text = btn.Text.ToLower();

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            if (text == "join")
            {
                ListBoxItem listItem = this.allGroup.SelectedItem as ListBoxItem;

                if (listItem != null)
                {
                    Group item = listItem.Content as Group;

                    //MessageBox.Show(item.TextTitle);

                    client.CreateLinkerAsync(item.Id, Global.UserInfo.UserID, 0, 2);

                    client.CreateLinkerCompleted += (s, args) =>
                    {
                        LoadListGroup();
                    };
                }
            }

            if (text == "refresh")
            {
                myStatus.ShowPopup("waitting loading group data in server ...!");
                LoadAllGroup();
                LoadListGroup();
                LoadInvateGroup();
            }

            if (text =="find")
            {
                InputPrompt input = new InputPrompt();
                input.Completed += (s, args) =>
                {
                    if (args.Result == "" && args.Result == null) return;

                    client.SearchGroupCompleted += (send, recive) =>
                    {
                        allGroup.Items.Clear();

                        List<List<string>> listdata = JsonConvert.DeserializeObject<List<List<string>>>(recive.Result);

                        if (listdata.Count == 0) { MessageBox.Show("no data!"); return; }

                        var data = Group.DeserializeObject(listdata);

                        foreach (Group item in data)

                            allGroup.Items.Add(item);
                    };
                    client.SearchGroupAsync(args.Result);
                };
                input.Title ="Find group by name";
                input.Message = "Please input group name your want find";
                input.Show();
            }

            if (text == "create")
            {
                InputPrompt input = new InputPrompt();
                input.Completed += (s, args) =>
                {
                    if (args.Result != "" && args.Result!=null)
                    {
                        client.CreateGroupCompleted += (send, recive) =>
                        {
                            LoadAllGroup();
                            LoadListGroup();
                        };
                        client.CreateGroupAsync(Global.UserInfo.UserID, args.Result, 1, 1);
                    }
                };
                input.Title = "Create Radar group";
                input.Message = "Please input group name:";
                input.Show();
            }
        }

        private void myGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
          //  
        }

        private void myGroup_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (FrameworkElement)e.OriginalSource;

            if (item != null)
            {
                Group data = item.DataContext as Group;

                if(data!=null)

                    NavigationService.Navigate(new Uri("/UIView/GroupMemberDlg.xaml?groupid=" + data.Id + "&owner=" + data.MyOwner, UriKind.RelativeOrAbsolute));
            }
        }

        private void agreeGroup_Click(object sender, RoutedEventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Please check data connect wifi/cellular...");

                return;
            }

            string header = (sender as MenuItem).Header.ToString();

            ListBoxItem listItem = this.invateGroup.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

            if (listItem != null)
            {
                mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

                Group item = listItem.Content as Group;

                client.UpdateLinkerAsync(item.Id, Global.UserInfo.UserID, 0, 1);

                client.UpdateLinkerCompleted += (s, args) =>
                {
                    MessageBox.Show("Your request has been sent successfully!");

                    LoadListGroup();

                    LoadInvateGroup();
                };
            }
        }
    }
    public class Group
    {
        public int Id { set; get; }
        public string Title { set; get; }
        public string Owner { get; set; }
        public int MyOwner { get; set; }
        public int Status { get; set; }

        public static List<Group> DeserializeObject(List<List<string>> data)
        {
            List<Group> result=new List<Group>();

            foreach (List<string> items in data)
            {
                if (items.Count >= 5)
                {
                    Group item = new Group()
                    {
                        Id=int.Parse(items[0]),
                        Title=items[1],
                        Owner=items[2],
                        MyOwner = int.Parse(items[3]),
                        Status= int.Parse(items[4])
                    };
                    result.Add(item);
                }
            }
            return result;
        }
    }
}